from django.shortcuts import render
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import mixins, generics, viewsets, filters
from rest_framework.pagination import PageNumberPagination

from app.goods.filters import GoodsFilter

"""
第一种方法继承APIView
class GoodsListView(APIView):
    '''
    商品列表
    '''

    def get(self, request, format=None):
        # 获取所有的商品信息， [object1, object2,........]
        goods = Goods.objects.all()
        # 根据指定的Seriializer进行序列化对象
        goods_serialzer = GoodsSerializer(goods, many=True)
        # 以REST需要的Response(状态码和数据信息)返回给用户
        return Response(goods_serialzer.data)
        
第二种方法继承generics.GenericAPIView
class GoodsListView(mixins.ListModelMixin,mixins.RetrieveModelMixin,generics.GenericAPIView):
    
    商品列表页
   
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    def get(self, request, *args, **kwargs):
    # 不需要自己编写list方法。
        return self.list(request, *args, **kwargs)

"""

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from app.goods.models import Goods, GoodsCategory
from app.goods.serializers import GoodsSerializer, CategorySerializer


class GoodsPagination(PageNumberPagination):
    '''
    商品列表自定义分页
    '''
    # 默认每页显示的个数
    page_size = 10
    # 可以动态改变每页显示的个数 # http://xxxx/goods/?page=2&page_size=5
    page_size_query_param = 'page_size'
    # 页码参数
    page_query_param = 'page' # http://xxxx/goods/?page=1
    # 最多能显示多少页
    max_page_size = 100

class GoodsListViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    """
    商品列表页
    """
    pagination_class = GoodsPagination
    queryset = Goods.objects.all().order_by('id')
    serializer_class = GoodsSerializer
    filter_backends = (DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter)
    # 设置filter的类为我们自定义的类
    filter_class = GoodsFilter
    search_fields = ('=name','goods_brief')
    # 排序
    ordering_fields = ('sold_num','add_time')

class CategoryViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    # '''
 	# list:
 	# 商品分类列表数据
 	# '''
    # queryset = GoodsCategory.objects.all()
    # 希望查询一级分类的信息
    queryset =  GoodsCategory.objects.filter(category_type=1)
    serializer_class = CategorySerializer



